package com.tools.cleanmaster.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.OnCompositionLoadedListener;
import com.hm.ads.sdk.HmAdsSDK;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ArgbEvaluator;
import com.tools.ad.EntranceType;
import com.tools.ad.FlavorType;
import com.tools.ad.adscene.inner.CommonInterstitialScene;
import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.BuildConfig;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanConstant;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.bean.AutoCleanFeature;
import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.controller.ITrashCleanListener;
import com.tools.cleanmaster.controller.ITrashScanListener;
import com.tools.cleanmaster.controller.TrashQuickHandler;
import com.tools.cleanmaster.functionpage.CenterCircleClick;
import com.tools.cleanmaster.functionpage.FunctionItem;
import com.tools.cleanmaster.functionpage.FunctionItemSharedPrefs;
import com.tools.cleanmaster.functionpage.FunctionPageState;
import com.tools.cleanmaster.functionpage.ScanAnimationManager;
import com.tools.cleanmaster.manager.CleanerNotificationManager;
import com.tools.cleanmaster.manager.SortProcessManager;
import com.tools.cleanmaster.manager.TrashManager;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.TrashViewData;
import com.tools.cleanmaster.model.TrashesData;
import com.tools.cleanmaster.model.item.AppTrashItem;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.store.GlobalConfigSharedPrefManager;
import com.tools.cleanmaster.store.ResultPageSharedPrefManager;
import com.tools.cleanmaster.ui.base.LOverlayRationale;
import com.tools.cleanmaster.ui.base.ResultSingleActivity;
import com.tools.cleanmaster.ui.card.TrashCardListener;
import com.tools.cleanmaster.ui.card.animator.AnimatorHelper;
import com.tools.cleanmaster.ui.card.animator.AnimatorListenerAdapter;
import com.tools.cleanmaster.ui.dialog.CommonDialog;
import com.tools.cleanmaster.ui.view.CommonWaveButton;
import com.tools.cleanmaster.ui.view.DynamicColorController;
import com.tools.cleanmaster.ui.view.MainPageTipView;
import com.tools.cleanmaster.ui.view.circle.TrashGreatCircleListener;
import com.tools.cleanmaster.ui.view.circle.TrashGreatCircleView;
import com.tools.cleanmaster.ui.view.header.HeadHelper;
import com.tools.cleanmaster.ui.view.trash.TrashApkGroup;
import com.tools.cleanmaster.ui.view.trash.TrashCleanLayout;
import com.tools.cleanmaster.ui.view.trash.TrashCleanListAdapter;
import com.tools.cleanmaster.ui.view.trash.TrashGroup;
import com.tools.cleanmaster.ui.view.trash.TrashMemGroup;
import com.tools.cleanmaster.ui.view.trash.TrashResidualGroup;
import com.tools.cleanmaster.ui.view.trash.TrashSysCacheGroup;
import com.tools.cleanmaster.ui.view.trash.TrashViewItem;
import com.tools.cleanmaster.ui.view.trash.TrashViewItemSingle;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.PackageUtils;
import com.tools.cleanmaster.utils.StringUtils;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 扫描垃圾首页
 */
public class MainActivity extends ResultSingleActivity implements OnClickListener, ITrashScanListener,
        OnChildClickListener, OnGroupClickListener, TrashCleanListAdapter.TrashScanListener {

    private static final int DELAY_CANCEL = 20 * 1000;
    private static final int SCANNING_VIEW_SCALE_TIME = 500;
    private static final float SCALE_TO_HALF_SIZE = 0.5f;
    private static final float TOTAL_SCALE_SIZE = 1f;
    private static final String TAG = "main";
    private static final long CLEAN_ALL_PROTECT_TIME = 2 * 60 * 1000;
    protected ExpandableListView mExplanListView;
    protected TrashCleanListAdapter mAdapter;
    private Context mContext;
    private CommonWaveButton mBottomBtn;
    private TextView mScanningContent;
    private TextView mScanningHead;
    private TrashCleanLayout mScanLayout;
    private TrashGreatCircleView mTrashScanView;
    private volatile ScanState mPageState;

    private RelativeLayout.LayoutParams mExplanListLayoutParams;

    // 扫描过程中临时记录扫描大小与进度
    private long mScanTotalSize = 0l;

    private long mScanStartTime;
    private long mLastCleanSize;
    private long mLastTotalSize;
    private int mFrom = 0;
    private int mCleanInnerCircleColor;

    private boolean isFirstPageState = false;
    private boolean mLastCleanAllDefault;

    private int mListViewMarginTop;
    private int mScanProgress = 0;

    private CommonDialog mCommonDialog;

    private HashMap<String, Integer> mGroupPositionMap = new HashMap<String, Integer>();

    private TrashViewData mTrashViewData;
    private MainPageTipView mMainPageTipView;

    private DynamicColorController mBgColorController;
    private DynamicColorController mShadeColorController;
    private DynamicColorController mInnerCircleColorController;

    private View mScanHeaderLayout;
    private View mTrashTopView;
    private View mWholeLayout;
    private View mFunctionHomePage;

    private ArgbEvaluator mColorEvaluator;
    private ScanAnimationManager scanAnimationManager;
    private ViewGroup.LayoutParams mScanLayoutParams;
    private TrashQuickHandler mTrashHandler = null;
    private boolean hasShowResultPage = false;
    private View mPerfectViewLayout;
    private LottieAnimationView mPerfectView;
    private boolean hasLoadedPerfect = false;
    private boolean haveRequestedInterstitialAdvert = false;//已请求了插屏广告
    TrashGreatCircleListener mGreatCircleListener = new TrashGreatCircleListener() {
        @Override
        public void onCleanFinish() {
            mCleanInnerCircleColor = getResources().getColor(R.color.common_background_blue);
            if (mPageState == ScanState.STATE_RESULT_SHOW) {
                LogHelper.d(CleanConstant.TAG, "on Clean Animation Finish");
                return;
            }
            beginCleanFinishUIOperation();
        }

        @Override
        public int setCleanBackgroundColor() {
            if (!isFirstPageState) {
                return mCleanInnerCircleColor;
            }
            return getResources().getColor(R.color.first_page_scan_inner_circle_color);
        }

        @Override
        public void onCleanAgainFinish() {

        }

        @Override
        public void onCleanProgress(int progress) {
            long size = mLastTotalSize;
            float fraction = 1 - progress / 360.0f;
            int startColor = DynamicColorController.getColorBySize(mContext, size, DynamicColorController.TYPE_BG);
            int startInnerCircleColor = DynamicColorController.getColorBySize(mContext, size, DynamicColorController.TYPE_INNER_CIRCLE);
            smoothColorChange(mWholeLayout, fraction, startColor, getResources().getColor(R.color.common_background_blue));
            int color = (Integer) mColorEvaluator.evaluate(fraction, startInnerCircleColor, getResources().getColor(R.color.primary_color));
            if (fraction < 0.1 && isFirstPageState) {
                isFirstPageState = false;
            }
            mCleanInnerCircleColor = color;
        }

        @Override
        public void onReScanFinish() {
            // 模拟清理结束
            mScanningContent.setVisibility(View.GONE);
            mScanningHead.setVisibility(View.GONE);
            MainActivity.this.removeEmptyMessage(R.id.msg_cleaner_home_fake_path);
            if (mCommonDialog != null) {
                mCommonDialog.dismiss();
            }
            cleanEnd(mContext, mLastCleanSize);
            mLastCleanAllDefault = true;

            if (imContext.getCleanRawCache().isHaveRequestedSplashAdvert()) {
                showResultPage();
            } else {
                mTrashScanView.needCleanAgain();
                disPlayPerfectView();
            }
        }
    };
    private android.animation.AnimatorListenerAdapter mPerfectAnimatorListener = new android.animation.AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(android.animation.Animator animation) {
            sendEmptyMessage(R.id.msg_hide_perfect_view, 2000L);
        }
    };
    private TrashCardListener trashCardListener = new TrashCardListener() {
        @Override
        public void onScanTrash() {
            com.tools.cleanmaster.ui.card.animator.AnimatorHelper.startTrashViewViAnim(mScanLayout,
                    new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mScanLayout.clearAnimation();
                            mScanLayout.setVisibility(View.VISIBLE);
                            mHeadTitle.setVisibility(View.GONE);
                            handleBottomBtnClick(true);
                            mIntervalTime = System.currentTimeMillis();
                        }
                    });
        }

    };

    @Override
    protected void setContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        setExitBy2Click(true);
        StatusBarUtil.setTransparent(this);

        Intent intent = getIntent();
        if (intent != null) {
            mFrom = intent.getIntExtra(CleanConstant.EXTRA_FROM_CLEAN_MASTER_KEY, 0);
        }
        reportFromStat();
        if (mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_TIME
                || mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_HOME) {
            CleanerNotificationManager.getInance(CleanApplication.getInstance()).cancel();
        }

        mContext = this;
        mColorEvaluator = new ArgbEvaluator();

        initViews();

        boolean isFirstStart = (GlobalConfigSharedPrefManager.hasWizardRun(CleanApplication.getInstance()) == -1);
        if (isFirstStart) {
            GlobalConfigSharedPrefManager.setWizardRun(CleanApplication.getInstance());
        }

        reportStatus();
        SortProcessManager.getSortProcessManager().startSort();
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);
        if (msg.what == R.id.msg_cleaner_home_fake_path) {
            String fakePath = (String) msg.obj;
            mScanningContent.setText(getResources().getString(R.string.trash_scanning_path, fakePath));

        } else if (msg.what == R.id.msg_ad_common_scene_loaded) {
            if (mCardListAdapter != null) {
                mCardListAdapter.notifyDataSetChanged();
            }
        } else if (msg.what == R.id.msg_show_first_page_scan) {
            startFirstPageScan();
        } else if (msg.what == R.id.msg_hide_perfect_view) {
            mPerfectViewLayout.setVisibility(View.GONE);
            beginCleanFinishUIOperation();

            if (haveRequestedInterstitialAdvert) {
                //显示插屏广告数据
                View advertView = imContext.getADModule().getAdSceneManager().getAdView(EntranceType.HOME_TRASH_INTERSTITIAL);
                if (advertView == null) {
                    sendEmptyMessage(R.id.msg_show_interstitial_advert, 1000L);
                }

                haveRequestedInterstitialAdvert = false;
            }
        } else if (msg.what == R.id.msg_reset_function_icon_state) {
            resetFunctionIconState();
        }
    }

    @Override
    protected void onPermissionGranted(List<String> permissions) {
        super.onPermissionGranted(permissions);
        if (permissions.contains(Permission.READ_PHONE_STATE)) {
            HmAdsSDK.getInstance().reInitDevice();
            imContext.handleMobEmptyMessage(R.id.msg_app_submit_referrer);
        }

        if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE)) {
            HmAdsSDK.getInstance().isLoadTrueUserCheck();
        }

        if (permissions.contains(Permission.WRITE_EXTERNAL_STORAGE) && permissions.contains(Permission.READ_PHONE_STATE)) {
            HmAdsSDK.getInstance().reInstallCheck();
        }

        if (mPageState == ScanState.STATE_RESULT_SHOW || mPageState == ScanState.STATE_SCAN_FINISHED) {
            requestOverlay(new LOverlayRationale());
        }
    }

    @Override
    protected void onPermissionDenied(List<String> permissions) {
        super.onPermissionDenied(permissions);
        if (permissions.contains(Permission.READ_PHONE_STATE)) {
            imContext.handleMobEmptyMessage(R.id.msg_app_submit_referrer);
        }
    }

    @Override
    protected void onOverlayPermissionGranted() {
        super.onOverlayPermissionGranted();
        GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SWITCH, CleanGAConstant.L_Overlay_Permission_Granted);
    }

    @Override
    protected void onOverlayPermissionDenied() {
        super.onOverlayPermissionDenied();
        GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SWITCH, CleanGAConstant.L_Overlay_Permission_Denied);
    }

    private void updateAutoCleanTipLayout() {
        if (!imContext.getCleanSharedPrefManager().isAutoCleanEnable(AutoCleanFeature.AUTO_CACHE) &&
                !imContext.getCleanSharedPrefManager().isAutoCleanEnable(AutoCleanFeature.AUTO_MEMORY)) {
            mMainPageTipView.setVisibility(View.VISIBLE);
        } else {
            mMainPageTipView.setVisibility(View.GONE);
        }

    }

    @Override
    protected void doOnResume() {
        if (null != scanAnimationManager) {
            resetFunctionIconState();
        }

        updateAutoCleanTipLayout();

        if (mScanLayout.getVisibility() != View.VISIBLE) {
            return;
        }

        if (mPageState == null) {
            long lastCleanAllDefault = GlobalConfigSharedPrefManager.getCleanAllDefaultTime(mContext);
            if (System.currentTimeMillis() - lastCleanAllDefault < CLEAN_ALL_PROTECT_TIME) {
                // 进入假扫描
                mPageState = ScanState.STATE_FAKE_RESCAN;
                String[] fakeScanningPaths = PackageUtils.allPackageNames(mContext);
                long time = SystemClock.uptimeMillis();
                for (String fakePath : fakeScanningPaths) {
                    Message message = Message.obtain();
                    message.what = R.id.msg_cleaner_home_fake_path;
                    message.obj = fakePath;
                    sendDelayMessage(message, time);
                    time += 100;
                }

                mScanningContent.setVisibility(View.VISIBLE);
                mScanningHead.setVisibility(View.VISIBLE);
                mBottomBtn.setEnabled(false);
                mBottomBtn.setText(R.string.trash_scanning);
                mTrashScanView.rescan(mGreatCircleListener);
                GlobalConfigSharedPrefManager.setScanTime(CleanApplication.getInstance(), System.currentTimeMillis());
                return;
            }

            // 重新进入界面，开始扫描
            logicStartScan();

        } else if (mPageState == ScanState.STATE_FAKE_RESCAN
                || mPageState == ScanState.STATE_RESULT_SHOW) {
            long lastCleanAllDefault = GlobalConfigSharedPrefManager.getCleanAllDefaultTime(mContext);
            if (System.currentTimeMillis() - lastCleanAllDefault > CLEAN_ALL_PROTECT_TIME
                    && lastCleanAllDefault != 0) {
                // 之前停留在假扫描，保护时间过后返回界面，重新开始扫描
                mBottomBtn.setEnabled(false);
                mBottomBtn.setVisibility(View.VISIBLE);
                logicStartScan();
            }
        }
    }

    private void reportFromStat() {
        if (mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_TIME) {
            // 上报通知栏-24小时间隔
        } else if (mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_HOME) {
            // 上报通知栏-点击home键
        } else {

        }
    }

    /**
     * 逻辑上启动扫描
     */
    private void logicStartScan() {
        GlobalConfigSharedPrefManager.setDeepClean(getApplicationContext());
        mScanStartTime = System.currentTimeMillis();
        mScanTotalSize = 0l;
        mScanProgress = 0;
        beginScanUIOperation();

        mTrashHandler = (TrashQuickHandler) TrashManager.getInstance().scan(this, false, false);
        // 扫描20s ，还在扫描状态，则停止
        ThreadPool.postOnWorkerDelayed(new Runnable() {
            @Override
            public void run() {
                if (mTrashHandler != null && mPageState == ScanState.STATE_SCANNING) {
                    mTrashHandler.cancelScan(true);
                }
            }
        }, DELAY_CANCEL);
    }

    private void initViews() {
        mHeader = HeadHelper.setupMainHeader(this, R.id.clean_main_title, R.string.app_name)
                .setSettingButton(R.drawable.menu_more, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupMenu(v);
                        mHeader.setNewLabel(false);
                    }
                }).setTriggerButton(R.drawable.main_trigger_ad, new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        imContext.getAdSceneManager().load(EntranceType.TRIGGER);
                        startActivity(new Intent(MainActivity.this, TriggerActivity.class));
                    }
                });

        if (mHeader != null) {
            mHeader.setNewLabel(!AutoCleanFeature.AUTO_CACHE.isEnable() && !AutoCleanFeature.AUTO_MEMORY.isEnable());
        }

        View title = findViewById(R.id.setting_layout);
        mSettingView = findViewById(R.id.settings);
        title.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupMenu(mSettingView);
            }
        });

        mBottomBtn = findViewById(R.id.bottom_button);
        mBottomBtn.setOnClickListener(this);

        mWholeLayout = findViewById(R.id.whole_layout);
        mWholeLayout.setBackgroundResource(R.drawable.single_result_bg);

        mScanLayout = findViewById(R.id.trash_clean_layout);
        mScanHeaderLayout = findViewById(R.id.trash_clean_header_layout);
        mTrashTopView = findViewById(R.id.scan_trash_top_layout);
        mTrashScanView = findViewById(R.id.trash_clean_view);
        mTrashScanView.setOnClickListener(this);
        mScanningContent = findViewById(R.id.trash_scanning_content);
        mScanningHead = findViewById(R.id.trash_scanning_head);
        mFunctionHomePage = findViewById(R.id.home_page_scan);
        mFunctionHomePage.setVisibility(View.GONE);

        mMainPageTipView = findViewById(R.id.main_auto_clean_setting_tips);

        mExplanListView = findViewById(R.id.list);
        mExplanListView.setClickable(false);
        mExplanListView.setOnChildClickListener(this);
        mExplanListView.setOnGroupClickListener(this);
        mExplanListView.setFadingEdgeLength(0);
        mExplanListLayoutParams = (RelativeLayout.LayoutParams) mExplanListView.getLayoutParams();
        mScanLayoutParams = mScanHeaderLayout.getLayoutParams();

        mBgColorController = new DynamicColorController(DynamicColorController.getColorBySize(
                mContext, 0, DynamicColorController.TYPE_BG), new DynamicColorController.DynamicColorListener() {
            @Override
            public void onColorChange(int color) {
                if (mFunctionHomePage.getVisibility() != View.VISIBLE && !FlavorType.FLAVOR_SUPERB.equals(BuildConfig.FLAVOR)) {
                    //                    mWholeLayout.setBackgroundColor(color);
                }
            }
        });
        mShadeColorController = new DynamicColorController(DynamicColorController.getColorBySize(
                mContext, 0, DynamicColorController.TYPE_SHADER), new DynamicColorController.DynamicColorListener() {
            @Override
            public void onColorChange(int color) {
                mTrashScanView.setShaderColor(color);
            }
        });
        mInnerCircleColorController = new DynamicColorController(
                DynamicColorController.getColorBySize(mContext, 0,
                        DynamicColorController.TYPE_INNER_CIRCLE), new DynamicColorController.DynamicColorListener() {
            @Override
            public void onColorChange(int color) {
                mCleanInnerCircleColor = color;
            }
        });

        mPerfectViewLayout = findViewById(R.id.lp_loading_card_perfect_rl);
        mPerfectView = findViewById(R.id.lp_loading_card_perfect_view);
        mPerfectView.addAnimatorListener(mPerfectAnimatorListener);

    }

    @Override
    public void onClick(View v) {
        if (v == mBottomBtn) {
            mBottomBtn.stop();
            handleBottomBtnClick(false);
            return;
        }

        FunctionItem item = FunctionItem.BATTERY;
        int i = v.getId();
        if (i == R.id.function_item_battery) {
            item = FunctionItemSharedPrefs.getFunctionItemNormal(mContext, FunctionItem.BATTERY) ? FunctionItem.BATTERY : FunctionItem.BATTERYOVER;
            if (BuildConfig.DEBUG) {
                item = FunctionItem.BATTERYOVER;
            }

        } else if (i == R.id.function_item_cpu) {
            item = FunctionItemSharedPrefs.getIsCpuNormal(mContext) ? FunctionItem.CPUCOOL : FunctionItem.CPUOVER;
            if (BuildConfig.DEBUG) {
                item = FunctionItem.CPUOVER;
            }

        } else if (i == R.id.function_item_booster) {
            item = FunctionItemSharedPrefs.getFunctionItemNormal(mContext, FunctionItem.BOOSTEROVER) ? FunctionItem.BOOSTER : FunctionItem.BOOSTEROVER;
            if (BuildConfig.DEBUG) {
                item = FunctionItem.BOOSTEROVER;
            }

        }

        Intent intent = new Intent(mContext, FunctionPageGuideActivity.class);
        intent.putExtra(FunctionPageGuideActivity.ITEM_EXTEA_FLAG, item.toString());
        mContext.startActivity(intent);
    }

    public void handleBottomBtnClick(boolean autoClean) {

        if (mPageState == ScanState.STATE_SCAN_FINISHED) {
            //开始请求广告(和SPLASH广告场景互斥)
            haveRequestedInterstitialAdvert = requestInterstitialAdvert(autoClean);

            GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_TRASH_RESULT_CLICK_BTN);
            if (mExplanListView.getVisibility() == View.VISIBLE) {
                resetTrashCleanViewState();
            }
            List<TrashItem> toCleanList = mAdapter.getSelectedTrahItems();
            mLastTotalSize = mTrashViewData.getTotalSize();
            mLastCleanSize = 0;
            for (TrashItem item : toCleanList) {
                mLastCleanSize += item.size;
            }

            mTrashHandler.clean(new ITrashCleanListener() {
                @Override
                public void onCleaned(int progress, long sizeCleaned, TrashType type) {

                }

                @Override
                public void onCleanStart() {

                }

                @Override
                public void onCleanFinish(long sizeCleaned) {

                }
            }, toCleanList);

            TrashesData trashesData = mTrashHandler.getTrashesData();
            mLastCleanAllDefault = !trashesData.isDefaultSelectCancel();
            if (mLastCleanAllDefault) {
                GlobalConfigSharedPrefManager.setCleanAllDefaultTime(mContext, System.currentTimeMillis());
            } else {
                GlobalConfigSharedPrefManager.setCleanAllDefaultTime(mContext, 0);
            }

            beginCleanUIOperation();
        } else if (mPageState == ScanState.STATE_RESULT_SHOW) {
            if (!mLastCleanAllDefault) {
                mExplanListLayoutParams.topMargin = getResources().getDimensionPixelSize(R.dimen.trash_clean_list_margintop);
                mExplanListView.setLayoutParams(mExplanListLayoutParams);
                mRope.setVisibility(View.GONE);
                if (mResultMultiCardLayout != null) {
                    mResultMultiCardLayout.setVisibility(View.INVISIBLE);
                }
                if (mResultSingleCardLayout != null) {
                    mResultSingleCardLayout.setVisibility(View.INVISIBLE);
                }

                mTrashScanView.needCleanAgain();
                if (!isFirstPageState) {
                    mBgColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_BG));
                }

                mShadeColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_SHADER));
                mInnerCircleColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_INNER_CIRCLE));

                long totalSize = mTrashViewData != null ? mTrashViewData.getTotalSize() : 0;
                if (totalSize <= 0) {
                    mTrashScanView.needCleanAgain();
                    disPlayPerfectView();
                } else {
                    beginScanFinishUIOperation();
                }

                return;
            }

            mLastTotalSize = 0;
            mLastCleanSize = 0;

            mTrashScanView.needCleanAgain();
            disPlayPerfectView();
        }
    }

    private void disPlayPerfectView() {
        mPageState = ScanState.STATE_PERFECT_SHOW;

        haveRequestedInterstitialAdvert = requestInterstitialAdvert();

        mScanLayout.setVisibility(View.GONE);
        mFunctionHomePage.setVisibility(View.GONE);
        mPerfectViewLayout.setVisibility(View.VISIBLE);
        if (hasLoadedPerfect) {
            mPerfectView.cancelAnimation();
            mPerfectView.setProgress(0);
            mPerfectView.playAnimation();
        } else {
            mPerfectView.setImageAssetsFolder(CleanConstant.ANIM_IMAGE_PATH + "function_complete");
            LottieComposition.Factory.fromAssetFileName(imContext, CleanConstant.ANIM_PATH + "function_complete.json", new OnCompositionLoadedListener() {
                @Override
                public void onCompositionLoaded(@Nullable LottieComposition composition) {
                    if (composition != null) {
                        hasLoadedPerfect = true;
                        mPerfectView.setComposition(composition);
                        mPerfectView.playAnimation();
                    }
                }
            });
        }
    }

    @Override
    public void onScanStart() {
        // do nothing
    }

    private void beginScanUIOperation() {
        mPageState = ScanState.STATE_SCANNING;
        mScanLayout.setIsScanFinished(false);
        mBgColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_BG));
        mShadeColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_SHADER));
        mInnerCircleColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_INNER_CIRCLE));
        mTrashScanView.setProgressLength(0);
        mTrashScanView.startScan();
        mBottomBtn.setEnabled(false);
        mBottomBtn.setText(R.string.trash_scanning);
        mBottomBtn.setVisibility(View.VISIBLE);
        mScanningContent.setVisibility(View.VISIBLE);
        mScanningHead.setVisibility(View.VISIBLE);
    }

    private void beginScanFinishUIOperation() {
        long totalSize = mTrashViewData != null ? mTrashViewData.getTotalSize() : 0;
        if (totalSize <= 0) {
            mTrashScanView.needCleanAgain();
            disPlayPerfectView();
            return;
        }

        mPageState = ScanState.STATE_SCAN_FINISHED;
        mScanLayout.setIsScanFinished(true);
        mTrashScanView.setProgressLength(360);

        changeBgColorBySize(totalSize);
        mScanLayout.setTrashSize(totalSize);
        mTrashScanView.setTrashSize(totalSize);
        mTrashScanView.invalidate();

        mBottomBtn.setText(R.string.cleanmaster_notification_button);
        mBottomBtn.setEnabled(true);
        mBottomBtn.start();
        mScanningContent.setVisibility(View.GONE);
        mScanningHead.setVisibility(View.GONE);
        mExplanListView.setClickable(true);
        if (mCommonDialog != null) {
            mCommonDialog.dismiss();
        }
        // 1.缓存、APK 和卸载残留默认展开;
        // 2.第一项强制展开，不管是什么内容
        Set<Entry<String, Integer>> entrySet = mGroupPositionMap.entrySet();
        for (Entry<String, Integer> entry : entrySet) {
            String name = entry.getKey();
            int position = entry.getValue();
            if (name.equals(TrashMemGroup.class.getSimpleName())
                    || name.equals(TrashSysCacheGroup.class.getSimpleName())) {
                mExplanListView.collapseGroup(position);
            } else {
                mExplanListView.expandGroup(position);
            }
        }
        if (!mGroupPositionMap.isEmpty()) {
            if (!mExplanListView.isGroupExpanded(0)) {
                mExplanListView.expandGroup(0);
            }
        }
        mExplanListView.setVisibility(View.VISIBLE);
        startTrashScanFinishAnim();

        requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE, Permission.ACCESS_FINE_LOCATION);
    }

    private void beginCleanUIOperation() {
        mTrashScanView.setVisibility(View.VISIBLE);
        mTrashTopView.setVisibility(View.GONE);
        mPageState = ScanState.STATE_CLEANING;
        mScanLayout.setIsCleaning(true);
        mBottomBtn.setEnabled(false);
        mBottomBtn.setText(R.string.trash_cleanning);
        mTrashScanView.setTrashSize(mLastCleanSize);
        mTrashScanView.setCleanSpeed(2);
        mTrashScanView.startClean(mGreatCircleListener);
    }

    private void beginCleanFinishUIOperation() {
        mScanLayout.setIsCleaning(false);
        mTrashScanView.setProgressLength(360);
        mTrashScanView.postInvalidate();
        mBottomBtn.setEnabled(true);
        mBottomBtn.setText(R.string.trash_scan_finish);
        mScanningContent.setVisibility(View.GONE);
        mScanningHead.setVisibility(View.GONE);
        if (mCommonDialog != null) {
            mCommonDialog.dismiss();
        }
        cleanEnd(this, mLastCleanSize);
        isFirstPageState = false;
        showResultPage();

        //显示插屏广告数据
        CommonInterstitialScene cleanDoneScene = (CommonInterstitialScene) imContext
                .getADModule()
                .getAdSceneManager()
                .getAdScene(EntranceType.HOME_TRASH_INTERSTITIAL);
        if (cleanDoneScene != null) {
            cleanDoneScene.showAd();
        }
    }

    @Override
    protected void onCleanResultAllAnimationEnd() {
        super.onCleanResultAllAnimationEnd();
        requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE, Permission.ACCESS_FINE_LOCATION);
    }

    @Override
    public void onScanProgressUpdate(final String desc, final int percent, final long size) {
        if (mPageState != ScanState.STATE_SCANNING) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(desc)) {
                    mScanningContent.setText(getResources().getString(
                            R.string.trash_scanning_path, desc));
                }
                if (percent != mScanProgress) {
                    mTrashScanView.setProgressLength((percent) * 360 / 100);
                    mScanProgress = percent;
                }
                if (size != mScanTotalSize) {
                    mTrashScanView.setTrashSize(size);
                    mTrashScanView.invalidate();
                    mScanLayout.setTrashSize(size);
                    changeBgColorBySize(size);
                    mScanTotalSize = size;
                }
            }
        });
    }

    @Override
    public void onScanTypeFinish(TrashType type, final long size) {
    }

    private void changeBgColorBySize(long size) {
        if (!isFirstPageState) {
            mBgColorController.setColor(DynamicColorController.getColorBySize(mContext, size, DynamicColorController.TYPE_BG));
        }
        mShadeColorController.setColor(DynamicColorController.getColorBySize(mContext, size, DynamicColorController.TYPE_SHADER));
        mInnerCircleColorController.setColor(DynamicColorController.getColorBySize(mContext, size, DynamicColorController.TYPE_INNER_CIRCLE));
    }

    private void smoothColorChange(View targetView, float fraction, int startColor, int endColor) {
        if (fraction > 1 || fraction < 0 || targetView == null) {
            return;
        }
        int color = (Integer) mColorEvaluator.evaluate(fraction, startColor, endColor);
//        targetView.setBackgroundColor(color);
    }

    @Override
    public void onScanFinish() {
        TrashesData trashesData = mTrashHandler.getTrashesData();
        CleanerNotificationManager.getInance(getApplicationContext()).sendScanNotification(
                getApplicationContext(), CleanConstant.PHONE_CLEANER_NOTIFICATION_HOME,
                trashesData.getSize());
        mTrashViewData = TrashViewData.createTrashViewData(trashesData);
        if (mTrashViewData != null) {
            mScanStartTime = 0;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter = onCreateTrashCleanListAdapter(mTrashViewData.getGroupList());
                    mExplanListView.setAdapter(mAdapter);

                    if (mTrashViewData.getTotalSize() / 1024 <= 0) {
                        if (imContext.getCleanRawCache().isHaveRequestedSplashAdvert()) {
                            beginScanFinishUIOperation();
                        } else {
                            mTrashScanView.needCleanAgain();
                            disPlayPerfectView();
                        }
                    } else {
                        beginScanFinishUIOperation();
                        mIntervalTime = System.currentTimeMillis();
                    }
                }
            });
        } else {
            if (imContext.getCleanRawCache().isHaveRequestedSplashAdvert()) {
                beginScanFinishUIOperation();
            } else {
                mTrashScanView.needCleanAgain();
                disPlayPerfectView();
            }
        }
    }

    private boolean requestInterstitialAdvert() {
        return requestInterstitialAdvert(true);
    }

    /**
     * 请求广告数据
     * 如果是用户手动点击，就无需判断是否有请求闪屏的广告
     *
     * @param autoClean
     * @return
     */
    private boolean requestInterstitialAdvert(boolean autoClean) {
        if (autoClean && imContext.getCleanRawCache().isHaveRequestedSplashAdvert()) {
            return false;
        }

        return imContext.getADModule().getAdSceneManager().load(EntranceType.HOME_TRASH_INTERSTITIAL);
    }

    void startTrashScanFinishAnim() {
        final int topMargin = mExplanListLayoutParams.topMargin;
        final int cleanViewHeight = mTrashScanView.getHeight();
        mScanLayout.resetScanFinshState();
        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.d(TAG, "init topMargin : " + mExplanListLayoutParams.topMargin);
        }
        AnimatorHelper.startZoomAnim(mContext, mTrashScanView,
                SCANNING_VIEW_SCALE_TIME, null, 0, 1, SCALE_TO_HALF_SIZE,
                new AnimatorHelper.ShrinkExplansionListener() {

                    @Override
                    public void update(float scaleSize) {
                        int translateY = (int) ((1 - scaleSize) * cleanViewHeight);
                        float fixedTopMargin = topMargin - translateY;
                        int topDistance = getResources().getDimensionPixelSize(
                                R.dimen.explansion_margin_top);
                        if (fixedTopMargin <= topDistance) {
                            fixedTopMargin = topDistance;
                        }
                        if (FeatureConfig.DEBUG_LOG) {
                            LogHelper.d(TAG, "up scaleSize " + scaleSize + " marginTop : "
                                    + fixedTopMargin);
                        }
                        mScanLayoutParams.height = (int) fixedTopMargin;
                        mScanHeaderLayout.setLayoutParams(mScanLayoutParams);
                        mExplanListLayoutParams.topMargin = (int) fixedTopMargin;
                        mExplanListView.setLayoutParams(mExplanListLayoutParams);
                        mScanLayout.handleTipsDisplay(mExplanListLayoutParams, false);
                    }

                }, new com.nineoldandroids.animation.AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        mTrashScanView.setVisibility(View.INVISIBLE);
                        mTrashTopView.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        mBottomBtn.setClickable(true);
                        mScanLayout.setIsScanFinished(true);
                        mTrashScanView.setVisibility(View.GONE);
                    }
                });
    }

    private void resetTrashCleanViewState() {
        mScanLayout.handleTipsDisplay(null, true);
        final float fromScaleSize = mScanLayout.isCircleShrink() ? 0f : SCALE_TO_HALF_SIZE;
        final float toScaleSize = TOTAL_SCALE_SIZE;
        final int cleanViewHeight = mTrashScanView.getHeight();
        final int bottomDistance = getResources().getDimensionPixelSize(R.dimen.trash_clean_list_margintop);
        mScanLayout.handleUpAnim(bottomDistance);
        if (mExplanListView.getVisibility() == View.VISIBLE) {
            mListViewMarginTop = mExplanListLayoutParams.topMargin;
        }
        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.d(TAG, "before reset margin Top " + mListViewMarginTop);
        }
        AnimatorHelper.startZoomAnim(mContext, mTrashScanView, SCANNING_VIEW_SCALE_TIME, null,
                0, fromScaleSize, toScaleSize, new AnimatorHelper.ShrinkExplansionListener() {

                    @Override
                    public void update(float scaleSize) {
                        if (mExplanListView.getVisibility() == View.VISIBLE) {
                            int translateY = (int) ((scaleSize - fromScaleSize) * cleanViewHeight);
                            float fixedTopMargin = mListViewMarginTop + translateY;
                            if (fixedTopMargin >= bottomDistance) {
                                fixedTopMargin = bottomDistance;
                            }
                            if (FeatureConfig.DEBUG_LOG) {
                                LogHelper.d(TAG, " down scaleSize " + scaleSize + "marginTop : "
                                        + fixedTopMargin);
                            }
                            mScanLayoutParams.height = (int) fixedTopMargin;
                            mScanHeaderLayout.setLayoutParams(mScanLayoutParams);
                            mExplanListLayoutParams.topMargin = (int) fixedTopMargin;
                            mExplanListView.setLayoutParams(mExplanListLayoutParams);
                        }
                    }

                }).addListener(new com.nineoldandroids.animation.AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                initAdapter();
                mScanLayout.setIsShrink(false);
                mExplanListView.setVisibility(View.GONE);
                mBottomBtn.setClickable(true);
            }
        });
    }

    private void initAdapter() {
        if (mTrashHandler == null) {
            return;
        }
        TrashesData trashesData = mTrashHandler.getTrashesData();
        trashesData.loadCheckDefault();
        mTrashViewData = TrashViewData.createTrashViewData(trashesData);
        if (mTrashViewData != null) {
            mAdapter = onCreateTrashCleanListAdapter(mTrashViewData.getGroupList());
            mExplanListView.setAdapter(mAdapter);
        }
    }

    protected TrashCleanListAdapter onCreateTrashCleanListAdapter(List<TrashGroup> groupList) {
        mGroupPositionMap.clear();
        for (int i = 0; i < groupList.size(); i++) {
            mGroupPositionMap.put(groupList.get(i).getClass().getSimpleName(), i);
        }
        return new TrashCleanListAdapter(mContext, groupList, this, this, mExplanListView);
    }

    @Override
    public void onScanStop() {
        // 超过20s，触发的自动停止也要走这个逻辑
        onScanFinish();
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
                                int childPosition, long id) {
        boolean isProgressing = mPageState == ScanState.STATE_SCANNING
                || mPageState == ScanState.STATE_CLEANING;
        if (!isProgressing) {
            TrashCleanListAdapter adapter = (TrashCleanListAdapter) parent
                    .getExpandableListAdapter();
            final TrashGroup group = adapter.getTrashGroups().get(groupPosition);
            final TrashViewItem viewItem = group.getChildItems().get(childPosition);
            showTrashInfoDialog(viewItem);
        }
        return false;
    }

    private void showTrashInfoDialog(TrashViewItem viewItem) {
        CommonDialog dialog = new CommonDialog(mContext);
        View content = LayoutInflater.from(this).inflate(R.layout.common_dialog_message, null);
        dialog.setContentView(content);
        dialog.setOkBtn(R.string.common_ok, null); //不设置，点击没有响应
        TextView message = content.findViewById(R.id.message);
        TextView path = content.findViewById(R.id.message_path);
        TextView size = content.findViewById(R.id.message_size);
        TextView time = content.findViewById(R.id.message_time);

        if (viewItem instanceof TrashApkGroup.ApkTrash) {
            final TrashApkGroup.ApkTrash apkTrash = (TrashApkGroup.ApkTrash) viewItem;
            dialog.setTitle(R.string.useless_apk_trash_item);
            message.setText(Html.fromHtml(getString(R.string.trash_clean_apk_dialog_message,
                    apkTrash.getTitle())));
            path.setText(Html.fromHtml(getString(R.string.trash_clean_path,
                    apkTrash.mApkItem.filePath)));
            size.setText(Html.fromHtml(getString(R.string.trash_clean_size,
                    StringUtils.getSizeString(apkTrash.mTrashItem.size))));
            File file = new File(apkTrash.mApkItem.filePath);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(file.lastModified()));
            time.setText(Html.fromHtml(getString(R.string.trash_clean_date, date)));
            dialog.show();
        } else if (viewItem instanceof TrashResidualGroup.AppResTrashItem) {
            TrashResidualGroup.AppResTrashItem residualItem = (TrashResidualGroup.AppResTrashItem) viewItem;
            dialog.setTitle(R.string.residual_uninstall_trash_item);
            message.setText(Html.fromHtml(mContext.getString(
                    R.string.trash_clean_app_residual_dialog_message, residualItem.getTitle())));

            size.setText(Html.fromHtml(getString(R.string.trash_clean_size,
                    StringUtils.getSizeString(residualItem.getTotalSize()))));
            path.setText(Html.fromHtml(getString(R.string.trash_clean_path,
                    residualItem.mTrashItem.filePath)));
            File file = new File(residualItem.mTrashItem.filePath);
            String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(file.lastModified()));
            time.setText(Html.fromHtml(getString(R.string.trash_clean_date, date)));

            dialog.show();
        } else if (viewItem instanceof TrashViewItemSingle) {
            final TrashItem trash = ((TrashViewItemSingle) viewItem).mTrashItem;
            if (trash.trashType == TrashType.APP_TRASH_FILE) {
                if (trash instanceof AppTrashItem) {
                    AppTrashItem appTrash = (AppTrashItem) trash;
                    dialog.setTitle(R.string.cache_trash_item);
                    message.setText(Html.fromHtml(getString(
                            R.string.trash_clean_app_cache_dialog_content, appTrash.itemName,
                            appTrash.appName)));

                    size.setText(Html.fromHtml(getString(R.string.trash_clean_size,
                            StringUtils.getSizeString(appTrash.size))));
                    path.setText(Html.fromHtml(getString(R.string.trash_clean_path,
                            appTrash.filePath)));
                    File file = new File(appTrash.filePath);
                    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(file
                            .lastModified()));
                    time.setText(Html.fromHtml(getString(R.string.trash_clean_date, date)));

                    dialog.show();
                } else {
                    if (FeatureConfig.DEBUG_LOG) {
                        LogHelper.d(CleanConstant.TAG,
                                "Unknow AppTrashItem type:" + trash.getClass());
                    }
                }
            }
        }
    }

    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        if (mExplanListView.isGroupExpanded(groupPosition)) {
            mExplanListView.collapseGroup(groupPosition);
        } else {
            mExplanListView.expandGroup(groupPosition);
        }
        return true;
    }

    @Override
    public void onTrashSizeChanged() {
        if (mPageState != ScanState.STATE_SCANNING) {
            long totalSize = mTrashViewData != null ? mTrashViewData.getTotalSize() : 0;
            long totalSelectedSize = mTrashViewData != null ? mTrashViewData.getSelectedSize() : 0;

            String value = "";
            boolean hasChildSelected = totalSelectedSize > 0;
            value = StringUtils.getSizeString(totalSelectedSize);
            mScanLayout.setTrashSize(totalSize);
            mTrashScanView.setTrashSize(totalSize);
            mTrashScanView.invalidate();
            mBottomBtn.setText(getString(R.string.trash_clean_oneshot, hasChildSelected ? value
                    : ""));
            mBottomBtn.setEnabled(hasChildSelected);
            if (hasChildSelected) {
                mBottomBtn.start();
            } else {
                mBottomBtn.stop();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (mPageState == ScanState.STATE_RESULT_ENTERING) {
            return;
        }

        if (mPageState == ScanState.STATE_PERFECT_SHOW) {
            return;
        }

        boolean isProgressing = mPageState == ScanState.STATE_SCANNING || mPageState == ScanState.STATE_CLEANING;
        if (!isProgressing) {
            processExit();
            return;
        }

        if (mCommonDialog == null) {
            mCommonDialog = new CommonDialog(mContext);
            String message = "";
            String title = "";
            if (mPageState == ScanState.STATE_CLEANING) {
                title = getString(R.string.trash_clean_stopped_dialog_title);
                message = getString(R.string.trash_clean_stopped_dialog_content);
            } else if (mPageState == ScanState.STATE_SCANNING) {
                title = getString(R.string.trash_scan_stopped_dialog_title);
                message = getString(R.string.trash_scan_stopped_dialog_content);
            }
            mCommonDialog.setTitle(title);
            mCommonDialog.setImageView(R.drawable.common_residua);
            mCommonDialog.setMessage(message);
            mCommonDialog.setOkBtn(0, new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mCommonDialog != null) {
                        mCommonDialog.dismiss();
                    }

                    GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_CLICK, CleanGAConstant.L_STOP_DIALOG_OK);

                    if (mPageState == ScanState.STATE_CLEANING) {
                        mTrashScanView.setCleanSpeed(360);
                        beginCleanFinishUIOperation();
                        mBgColorController.setColor(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_BG));
                        mBgColorController.end();
                    } else if (mPageState == ScanState.STATE_SCANNING) {
                        if (mTrashHandler != null) {
                            mTrashHandler.cancelScan(true);
                        }
                    }
                }
            });
            mCommonDialog.setCancelBtn(0, null);
        }

        if (mCommonDialog != null) {
            mCommonDialog.show();
        }
    }

    private void processExit() {
        if (mFunctionHomePage.getVisibility() == View.VISIBLE) {
            if (exitBy2Click()) {
                if (scanAnimationManager != null) {
                    scanAnimationManager.releaseResources();
                }

                imContext.getCleanRawCache().setHaveRequestedSplashAdvert(false);

                if (hasShowResultPage) {
                    GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_FINISH, CleanGAConstant.L_APPLICATION_TRASH_RESULT);
                }
            }
        } else if (mPageState == ScanState.STATE_SCAN_FINISHED || mPageState == ScanState.STATE_RESULT_SHOW || isResultShow()) {
            startFirstPageScan();
            imContext.getAdSceneManager().release(EntranceType.HOME_TRASH_COMPLETED);
            if (mPageState == ScanState.STATE_SCAN_FINISHED) {
                GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SHOW, CleanGAConstant.L_HOME_FROM_TRASH_RESULT);
            }
        }
    }

    /**
     * 清理完成进行调用,展示rate或者分享
     */
    private void cleanEnd(Context context, long totalSize) {
        long size = GlobalConfigSharedPrefManager.getTrashCleanTotal(context) + totalSize;
        // 保存清理总量
        GlobalConfigSharedPrefManager.setTrashCleanTotal(context, size);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && mFrom <= 0) {
            mFrom = intent.getIntExtra(CleanConstant.EXTRA_FROM_CLEAN_MASTER_KEY, 0);
        }
        reportFromStat();
        if (mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_TIME
                || mFrom == CleanConstant.PHONE_CLEANER_FROM_NOTIFICATION_HOME) {
            CleanerNotificationManager.getInance(CleanApplication.getInstance()).cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCommonDialog != null) {
            if (mCommonDialog.isShowing()) {
                mCommonDialog.dismiss();
            }
            mCommonDialog = null;
        }
        SortProcessManager.getSortProcessManager().onDestroyProcess();
    }

    private void showResultPage() {
        mPageState = ScanState.STATE_RESULT_ENTERING;
        hasShowResultPage = true;
        GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SHOW, CleanGAConstant.L_TRASH_RESULT);

        switch (getResultPageType()) {
            case MultiCardPage:
                startMultiCardAnim();
                break;
            case SingleCardPage:
                startSingleCardResultAnim();
                break;
            default:
                break;
        }
    }

    @Override
    protected void resultPageShowFinish() {
        mPageState = ScanState.STATE_RESULT_SHOW;
    }

    //设置卡片head文案
    @Override
    protected void setCardHeadTitle() {
        long leftOverSize = mLastTotalSize - mLastCleanSize;
        switch (getResultPageType()) {
            case MultiCardPage:
                if (mLastTotalSize > 0) {
                    mResultMultiCardLayout.setHeadTitle(Html.fromHtml(getString(R.string.header_title, StringUtils.getSizeString(mLastCleanSize))));
                } else {
                    mResultMultiCardLayout.setHeadTitle(getString(R.string.scan_end_no_trash));
                }
                break;
            case SingleCardPage:
                if (mLastTotalSize > 0) {
                    String[] sizeUnitString = StringUtils.getSizeUnitString(mLastCleanSize);
                    mResultSingleCardLayout.setDisplayResult(sizeUnitString[0], sizeUnitString[1]);
                } else {
                    mResultSingleCardLayout.setDisplayResult("", getString(R.string.scan_end_no_trash));
                }
                break;
        }
        GlobalConfigSharedPrefManager.setLeftOverSize(CleanApplication.getInstance(), leftOverSize);
    }

    @Override
    protected void hideBackground() {
        mBgColorController.reset(DynamicColorController.getColorBySize(mContext, 0, DynamicColorController.TYPE_BG));
        mScanLayout.setVisibility(View.GONE);
    }

    @Override
    protected void setLastCleanSize() {
        ResultPageSharedPrefManager.setLastCleanAllDefault(mLastCleanAllDefault);
    }

    @Override
    protected TrashCardListener getTrashCardListener() {
        return trashCardListener;
    }

    @Override
    protected EntranceType getEntranceType() {
        return EntranceType.HOME_TRASH_COMPLETED;
    }

    @Override
    public ResultPageType getResultPageType() {
        return ResultPageType.MultiCardPage;
    }

    private void reportStatus() {

    }

    private void startFirstPageScan() {

        requestOverlay(new LOverlayRationale());

        isFirstPageState = true;
        hideResultPageCard();
        hideBackground();
        long totalSize = 0;

        if (mPageState == ScanState.STATE_SCAN_FINISHED) {
            totalSize = mTrashViewData != null ? mTrashViewData.getTotalSize() : 0;
            GlobalConfigSharedPrefManager.setLeftOverSize(CleanApplication.getInstance(), totalSize);
        }

        mHeadTitle.setVisibility(View.INVISIBLE);
        mFunctionHomePage.setVisibility(View.VISIBLE);
        mFunctionHomePage.setClickable(true);

        updateAutoCleanTipLayout();

        scanAnimationManager = new ScanAnimationManager(mWholeLayout, this, new CenterCircleClick() {
            @Override
            public void click() {
                imContext.getCleanRawCache().setHaveRequestedSplashAdvert(false);

                mFunctionHomePage.setClickable(false);
                scanAnimationManager.releaseResources();
                mPageState = ScanState.STATE_RESULT_SHOW;
                getTrashCardListener().onScanTrash();
            }
        });

        scanAnimationManager.setState(mLastCleanAllDefault ? FunctionPageState.BLUE : FunctionPageState.YELLOW);
        scanAnimationManager.startAnimation(mPageState != ScanState.STATE_SCAN_FINISHED);

        mWholeLayout.findViewById(R.id.function_item_battery).setOnClickListener(this);
        mWholeLayout.findViewById(R.id.function_item_cpu).setOnClickListener(this);
        mWholeLayout.findViewById(R.id.function_item_booster).setOnClickListener(this);
    }

    private void hideResultPageCard() {
        if (mResultMultiCardLayout != null) {
            mResultMultiCardLayout.setVisibility(View.GONE);
            mResultMultiCardLayout = null;
        }
        if (mResultSingleCardLayout != null) {
            mResultSingleCardLayout.setVisibility(View.GONE);
            mResultSingleCardLayout = null;
        }
    }


    public void resetFunctionIconState() {
        boolean isNormal;
        isNormal = FunctionItemSharedPrefs.getIsCpuNormal(mContext);
        ((ImageView) findViewById(R.id.cpu_icon)).setImageResource(isNormal ? R.drawable.function_item_cpu : R.drawable.function_cpu_over);
        if (!isNormal) {
            FunctionItemSharedPrefs.setItemOverLastShowTime(mContext, FunctionItem.CPUOVER);
        }
        isNormal = FunctionItemSharedPrefs.getFunctionItemNormal(mContext, FunctionItem.BATTERY);
        ((ImageView) findViewById(R.id.battery_icon)).setImageResource(isNormal ? R.drawable.function_item_battery : R.drawable.function_battery_over);

        if (!isNormal) {
            FunctionItemSharedPrefs.setItemOverLastShowTime(mContext, FunctionItem.BATTERYOVER);
        }
        isNormal = FunctionItemSharedPrefs.getFunctionItemNormal(mContext, FunctionItem.BOOSTEROVER);
        ((ImageView) findViewById(R.id.booster_icon)).setImageResource(isNormal ? R.drawable.function_item_booster : R.drawable.function_item_booster_over);
        if (!isNormal) {
            FunctionItemSharedPrefs.setItemOverLastShowTime(mContext, FunctionItem.BOOSTEROVER);
        }

    }

    public enum ScanState {
        STATE_SCANNING,
        STATE_SCAN_FINISHED,
        STATE_CLEANING,
        STATE_RESULT_SHOW,
        STATE_FAKE_RESCAN,
        STATE_RESULT_ENTERING,
        STATE_PERFECT_SHOW,
    }

}
